import { MessageType } from '@/config';
import { gigaResourceStorage } from '@/entrypoints/background';
import { ProductInfo } from '@/lib/dianxiaomi';
import { getGigaProductInfo as getGigaProductInfoUtil, getGigaSkuAndProductId } from '@/lib/giga';
import { useSettingsStore } from '@/store';
import { OperationMessageType } from '@/store/message';
import { useMessage } from './useDiaoxiaomiMessage';
import { useSave } from '../../hook/useSave';
export function useGiga() {
  const accountSetting = useSettingsStore((state) => state.accountSetting);
  const { resetMessage, addMessage } = useMessage();
  const { saveGigaResource } = useSave({
    addMessage,
  });
  async function getGigaProductInfo(productInfo: ProductInfo) {
    const gigaProductInfo = await getGigaProductInfoUtil(productInfo, accountSetting.giga);
    return gigaProductInfo;
  }

  async function getGigaDetailResource(
    productInfo: Partial<ProductInfo>,
    directoryHandle: FileSystemDirectoryHandle,
  ) {
    // console.log(productInfo, directoryHandle);
    if (productInfo.skuIdInfo) {
      const [, gigaProductId] = getGigaSkuAndProductId(productInfo.skuIdInfo);
      addMessage({
        category: productInfo.skuIdInfo,
        type: OperationMessageType.info,
        message: `开始下载 giga 中的详细资源(需要等待一定的时间)`,
      });
      const zipBlobResult = await browser.runtime.sendMessage({
        type: MessageType.getGigaResource,
        data: {
          gigaProductId,
        },
      });
      // console.log(zipBlobResult);
      if (zipBlobResult.code === 0) {
        addMessage({
          category: productInfo.skuIdInfo,
          type: OperationMessageType.success,
          message: `成功获取资源包`,
        });
        const zipBlobDataUrl = await gigaResourceStorage.getValue();
        const response = await fetch(zipBlobDataUrl!);
        const blob = await response.blob();
        await saveGigaResource({
          blob,
          skuIdInfo: productInfo.skuIdInfo,
          directoryHandle,
        });
        addMessage({
          category: productInfo.skuIdInfo!,
          type: OperationMessageType.success,
          message: `成功把资源保存到货号目录下 ${doneMessage}`,
        });
      } else {
        throw new Error(`下载 giga 中的详细资源失败: ${zipBlobResult.msg}`);
      }
    }
  }

  return {
    getGigaProductInfo: useCallback(getGigaProductInfo, [accountSetting]),
    getGigaDetailResource: useCallback(getGigaDetailResource, [saveGigaResource]),
  };
}

export function useGigaAccessToken() {
  const clientId = useSettingsStore((state) => state.accountSetting.giga.clientId);
  const clientSecret = useSettingsStore((state) => state.accountSetting.giga.clientSecret);
  const dispatch = useSettingsStore((state) => state.dispatch);
  const { gigaAccessTokenUpdateFrequency } = useAppConfig();

  console.log(clientId);

  // 每隔一段时间更新 access token
  useEffect(() => {
    async function updateAccessToken() {
      const accessTokenRes = await browser.runtime.sendMessage({
        type: MessageType.getGigaAccessToken,
        data: {
          clientId: clientId,
          clientSecret: clientSecret,
        },
      });
      console.log('获取到的 giga 的 token 信息', accessTokenRes);
      if (accessTokenRes.code === 0) {
        dispatch({
          type: 'update',
          update(draftState) {
            draftState.accountSetting.giga.accessToken = accessTokenRes.data.access_token;
            draftState.accountSetting.giga.tokenType = accessTokenRes.data.token_type;
          },
        });
      } else {
        // 如果获取失败,那么什么不做
        console.log(accessTokenRes);
      }
    }
    // 开始时先执行一次
    updateAccessToken();
    const timer = setInterval(() => {
      updateAccessToken();
    }, gigaAccessTokenUpdateFrequency * 1000);

    return () => {
      // 清理定时器
      clearInterval(timer);
    };
  }, [clientId, clientSecret]);
}
